package com.xjgc.common.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
public class AccessAPIUtil {

    public static String pushData(String url, String val) throws ResourceAccessException {
        RestTemplate restTemplate = new RestTemplate();
        for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
            }
        }
        HttpHeaders httpHeaders = new HttpHeaders();

        //   httpHeaders.setContentType(org.springframework.http.MediaType.parseMediaType("application/json; charset=UTF-8"));
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        //   httpHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        //      httpHeaders.set(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, "application/json");
        //      httpHeaders.set(javax.ws.rs.core.HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.toString());
        //  String jsonString= JSONObject.toJSONString(object, SerializerFeature.WriteMapNullValue);
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();

        val = val.replaceAll("(\\\\r\\\\n)", "");
        paramMap.add("sapXmlData", val);

        HttpEntity httpEntity = new HttpEntity(paramMap, httpHeaders);

        String result = "";
        int status = 0;
        try {
            ResponseEntity resp = restTemplate.postForEntity(url, httpEntity, String.class);
            result = resp.getBody().toString();
            status = resp.getStatusCode().value();
            log.info(status + "<-->" + result);
        } catch (Exception e) {
            log.info("访问发生异常：url = [" + url + "],  object = [" + val + "]");
            e.printStackTrace();

        }
        return result;
    }


    public static <T> String pushDataForObject(String url, List<T> list) throws ResourceAccessException {
        RestTemplate restTemplate = new RestTemplate();
        for (HttpMessageConverter<?> httpMessageConverter : restTemplate.getMessageConverters()) {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName("UTF-8"));
            }
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONArray sendJson = JSONArray.parseArray(JSON.toJSONString(list));

        HttpEntity httpEntity = new HttpEntity(sendJson, httpHeaders);

        String result = "";
        int status = 0;
        try {
            ResponseEntity resp = restTemplate.postForEntity(url, httpEntity, String.class);
            result = resp.getBody().toString();
            status = resp.getStatusCode().value();
            log.info(status + "<-->" + result);
        } catch (Exception e) {
//            log.info("访问发生异常：url = [" + url + "],  object = [" + jsonString + "]");
            e.printStackTrace();

        }
        return result;
    }


    public static <T> Result postRequest(String pushUrl, List<T> list) {
        Result<List<T>> returnResult = new Result<>();
        returnResult.setResult(list);
        JSONArray sendJson = JSONArray.parseArray(JSON.toJSONString(list));
        log.info("开始推送-->[{}]-[{}]", pushUrl, sendJson);
        //设置http请求头
        HttpHeaders headers = getHeaders();
        HttpEntity requestEntity = new HttpEntity(sendJson, headers);
        RestTemplate restTemplate = getRestTemplate();
        try {
            Result result = restTemplate.postForObject(pushUrl, requestEntity, Result.class);
            //log.info("推送完成-->[{}]-[{}]", pushUrl, sendJson);
            if (result.isSuccess()) {
                log.info(result.getMessage());
                returnResult.setSuccess(true);
            } else {
                returnResult.setSuccess(false);
                returnResult.setMessage(result.getMessage());
//                if ("2001".equals(result.getCode()) || "插入数据库失败".equals(result.getMessage())) {
//                    log.error("中间库接收失败:" + result.getMessage());
//                    returnResult.setSuccess(false);
//                    returnResult.setMessage("中间库接收失败:" + result.getMessage());
//                } else if ("3001".equals(result.getCode()) || "SAP接收数据失败".equals(result.getMessage())) {
//                    log.warn("中间库接收成功:" + result.getMessage());
//                    returnResult.setSuccess(true);
//                    returnResult.setMessage("中间库接收成功:" + result.getMessage());
//                }
            }
        } catch (RestClientException e) {
            String message = e.getMessage();
            if (message.contains("Connection refused") || message.contains("connect timed out")) {
                log.error("推送失败,无法访问服务地址!-->{}", message);
                returnResult.setSuccess(false);
                returnResult.setMessage("无法访问服务地址:" + message);
            } else if (message.contains("Read timed out")) {
                returnResult.setSuccess(true);
                returnResult.setMessage("推送成功,响应超时!" + message);
            }
        }
        return returnResult;
    }

    /**
     * 设置http请求头
     *
     * @return
     */
    public static HttpHeaders getHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json");
        headers.add("Content-Encoding", "UTF-8");
        headers.add("Content-Type", "application/json; charset=UTF-8");
        return headers;
    }

    /**
     * 设置请求参数
     *
     * @return
     */
    public static RestTemplate getRestTemplate() {
        // 设置超时  时间单位为毫秒 1分钟
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //链接超时 10 秒
        factory.setConnectTimeout(10 * 1000);
        //读取超时 60 秒
        factory.setReadTimeout(60 * 1000);
//        RestTemplate restTemplate = SpringContextUtils.getBean(RestTemplate.class);
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }


}
